/*
 *  author: Honrun
 */
#include "CSU8RP3216.h"
#include "stdint.h"
#include "DevicesTime.h"
#include "DevicesSoftTimer.h"




int8_t cSoftTimerSet(SoftTimerTypeDef *ptypeTimer, uint32_t ulTime, SoftTimerStateEnum state)
{
    if(ptypeTimer == NULL)
        return -1;

    ptypeTimer->timeStop = ulSoftTimerGetNow() + ulTime;
    ptypeTimer->timeDuration = ulTime;
    ptypeTimer->state = state;

    return 0;
}

int8_t cSoftTimerReset(SoftTimerTypeDef *ptypeTimer)
{
    if(ptypeTimer == NULL)
        return -1;

    cSoftTimerSet(ptypeTimer, ptypeTimer->timeDuration, ptypeTimer->state | softTimerOpen);

    return 0;
}

int8_t cSoftTimerReload(SoftTimerTypeDef *ptypeTimer)
{
    if(ptypeTimer == NULL)
        return -1;

    ptypeTimer->timeStop += ptypeTimer->timeDuration;
    ptypeTimer->state |= softTimerOpen;

    return 0;
}

int8_t cSoftTimerOpen(SoftTimerTypeDef *ptypeTimer)
{
    if(ptypeTimer == NULL)
        return -1;

    ptypeTimer->state |= softTimerOpen;

    return 0;
}

int8_t cSoftTimerClose(SoftTimerTypeDef *ptypeTimer)
{
    if(ptypeTimer == NULL)
        return -1;

    ptypeTimer->state &= ~softTimerOpen;

    return 0;
}

int8_t cSoftTimerSetState(SoftTimerTypeDef *ptypeTimer, SoftTimerStateEnum enumState)
{
    if(ptypeTimer == NULL)
        return -1;

    ptypeTimer->state = enumState;

    /* 设置为本次立即触发 */
    if(enumState & softTimerOver)
        ptypeTimer->timeStop = ulSoftTimerGetNow();

    return 0;
}

SoftTimerStateEnum enumSoftTimerGetState(SoftTimerTypeDef *ptypeTimer)
{
    uint32_t uiTimeStart = 0;

    if(ptypeTimer == NULL)
        return softTimerError;

    if((ptypeTimer->state & softTimerOpen) == 0)
        return softTimerClose;

    uiTimeStart = ptypeTimer->timeStop - ptypeTimer->timeDuration;
    if(ptypeTimer->timeStop >= uiTimeStart)
    {
        if((ulSoftTimerGetNow() >= ptypeTimer->timeStop) || (ulSoftTimerGetNow() < uiTimeStart))
            return softTimerOver;
    }
    else
    {
        if((ulSoftTimerGetNow() >= ptypeTimer->timeStop) && (ulSoftTimerGetNow() <= uiTimeStart))
            return softTimerOver;
    }

    return softTimerOpen;
}

/* 单位us */
uint32_t ulSoftTimerGetNow(void)
{
    uint32_t lTimeStamp = 0;

    lTimeStamp = lTimeGetStamp();

    return lTimeStamp;
}
